/**
 * 该插件可根据菜单配置自动生成 ANTD menu组件
 * menuData示例：
 * [
 *  {
 *    name: '菜单标题',
 *    img: '菜单图标',
 *    url: '菜单路由',
 *    invisible: 'boolean, 是否不可见',
 *    children: [子菜单配置]
 *  },
 *  {
 *    name: '菜单标题',
 *    img: '菜单图标',
 *    url: '菜单路由',
 *    invisible: 'boolean, 是否不可见',
 *    children: [子菜单配置]
 *  }
 * ]
 */
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { State, Mutation } from 'vuex-class'
import { Menu, Icon } from 'ant-design-vue'
import { IMenu } from '@/store/modules/permission'
const { Item, SubMenu } = Menu

// 默认菜单图标数组，如果菜单没配置图标，则会设置从该数组随机取一个图标配置
const iconArr: string[] = [
  'dashboard',
  'user',
  'form',
  'setting',
  'message',
  'safety',
  'bell',
  'delete',
  'code-o',
  'poweroff',
  'eye-o',
  'hourglass'
]

@Component
export default class IMenuComponent extends Vue {
  @Prop({
    type: Array,
    required: true
  })
  public menuData!: any

  @Prop({
    type: String,
    required: false,
    default: 'dark'
  })
  public theme!: string

  @Prop({
    type: String,
    required: false,
    default: 'inline'
  })
  public mode!: string

  @Prop({
    type: Boolean,
    required: false,
    default: false
  })
  public collapsed!: boolean

  @Prop({
    type: Object,
    default() {
      return {}
    }
  })
  public options!: any

  @Mutation('CHANGE_CURRENT_MENUID')
  public CHANGE_CURRENT_MENUID: any

  public openKeys: any[] = []
  public selectedKeys: any[] = []
  public cachedOpenKeys: any[] = []

  // 默认字段配置
  public defaultOptions = {
    name: 'name', // 菜单名称
    path: 'path', // 菜单跳转地址
    icon: 'icon', // 菜单图标
    children: 'children', // 子菜单
  }

  // 菜单配置
  get menuOptions() {
    return Object.assign({}, this.defaultOptions, this.options)
  }

  get rootSubmenuKeys() {
    return this.menuData.map((item: any) => item.path)
  }

  public created() {
    this.updateMenu()
  }

  @Watch('collapsed')
  public onCollapsedChanged(val: boolean) {
    if (val) {
      this.cachedOpenKeys = this.openKeys
      this.openKeys = []
    } else {
      this.openKeys = this.cachedOpenKeys
    }
  }

  @Watch('$route')
  public onRouterChanged() {
    this.updateMenu()
  }

  // @Watch('selectedKeys')
  // public onSelectedKeysChanged(val: any[]) {
  //   this.changeMenuId(val[0])
  // }

  // public changeMenuId(path: string) {
  //   let menuId: string = ''
  //   let data: any = this.menuData
  //   let len: number = data.length
  //   if (len > 0) {
  //     for (let i = 0; i < len; i++) {
  //       if (data[i].children && data[i].children.length) {
  //         getId(data[i].children)
  //       } else {
  //         if (path === data[i].path) {
  //           menuId = data[i]._id
  //         }
  //       }
  //     }
  //   }
  //   function getId(children: any[]) {
  //     children.map((item: any) => {
  //       if (item.children && item.children.length) {
  //         getId(item.children)
  //       } else {
  //         if (path === item.path) {
  //           menuId = item._id
  //         }
  //       }
  //     })
  //   }
  //   this.CHANGE_CURRENT_MENUID(menuId)
  //   // console.log(menuId)
  // }

  public renderIcon(h: any, icon: any) {
    return !icon
      ? null
      : h(Icon, {
        // 随机获取图标 iconArr[Math.floor((Math.random() * iconArr.length))]
        props: { type: icon ? icon : '' }
      })
  }
  public renderMenuItem(h: any, menu: any, pIndex: any, index: any) {
    return h(
      Item,
      {
        key: menu.path ? menu.path : 'item_' + pIndex + '_' + index
      },
      [
        h('a', { attrs: { href: '#' + menu.path, 'data-id': menu.id } }, [
          this.renderIcon(h, menu.meta.icon),
          h('span', [menu.meta.title])
        ])
      ]
    )
  }
  public renderSubMenu(h: any, menu: IMenu, pIndex: number, index: number) {
    const subItem = [
      h('span', { slot: 'title' }, [
        this.renderIcon(h, menu.meta ?.icon),
        h('span', [menu.meta ?.title])
      ])
    ]
    let itemArr: any[] = []
    let pIndexNew: string = pIndex + '_' + index
    if (menu.children && menu.children.length) {
      itemArr = menu.children.map((item: IMenu, i: number) => this.renderItem(h, item, pIndexNew, i));
    }
    return h(
      SubMenu,
      { key: menu.path ? menu.path : 'submenu_' + pIndexNew },
      subItem.concat(itemArr)
    )
  }
  public renderItem(h: any, menu: IMenu, pIndex: any, index: any) {
    if (!menu.invisible) {
      return menu.children && menu.children.length
        ? this.renderSubMenu(h, menu, pIndex, index)
        : this.renderMenuItem(h, menu, pIndex, index)
    }
  }
  public renderMenu(h: any, menuTree: IMenu[]) {
    return menuTree.map((menu: IMenu, i: number) => this.renderItem(h, menu, '0', i));
  }
  public onOpenChange(openKeys: string[]) {
    // const latestOpenKey = openKeys.find(
    //   (key: string) => this.openKeys.indexOf(key) === -1
    // )
    // console.log(openKeys)
    // console.log(this.openKeys)
    // console.log(this.rootSubmenuKeys)
    this.openKeys = openKeys
    // if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
    //   this.openKeys = openKeys
    // } else {
    //   this.openKeys = latestOpenKey ? [latestOpenKey] : []
    // }
  }
  public updateMenu() {
    let routes: any[] = this.$route.matched.concat()
    this.selectedKeys = [routes.pop().path]
    // let openKeys: any[] = []
    // routes.forEach((item: any) => {
    //   openKeys.push(item.path)
    // })
    // this.collapsed || this.mode === 'horizontal' ? this.cachedOpenKeys = openKeys : this.openKeys = openKeys
  }

  public render(h: any) {
    return h(
      Menu,
      {
        props: {
          // inlineCollapsed: true,
          theme: this.$props.theme,
          mode: this.$props.mode,
          openKeys: this.openKeys,
          selectedKeys: this.selectedKeys
        },
        on: {
          openChange: this.onOpenChange,
          select: (obj: any) => {
            this.selectedKeys = obj.selectedKeys
            this.$emit('select', obj)
          }
        }
      },
      this.renderMenu(h, this.menuData)
    )
  }
}
